package com.bjsxt.userscenter.head.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bjsxt.userscenter.common.controller.BaseController;
import com.bjsxt.userscenter.common.util.ConstatFinalUtil;
import com.bjsxt.userscenter.common.util.EncryptUtil;
import com.bjsxt.userscenter.outer.service.IOuterService;
import com.bjsxt.userscenter.users.pojo.AUsers;
import com.bjsxt.userscenter.users.pojo.AUsersEnum;
import com.bjsxt.userscenter.users.pojo.AUsersExtend;
import com.bjsxt.userscenter.users.service.IUsersService;

/**
 * 前台(广大网民)
 * @author wangshSxt
 *
 */
@Controller
public class NoLoginController extends BaseController
{
	@Resource
	private IUsersService usersService;
	@Resource
	private IOuterService outerService;
	
	/**
	 * 打开登陆页面
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.LOGGER.info("--- login ---");
		HttpSession session = request.getSession() ; 
		/* 如果session有管理员,说明已经登陆 */
		AUsers users = (AUsers) session.getAttribute("users");
		if(users != null)
		{
			/* 已经登陆 */
			if(this.returnUrl(request,response,users))
			{
				return null ; 
			}else
			{
				/* 登陆成功 */
				return "redirect:/head/users/main.htm";
			}
		}
		return "/head/login" ; 
	}
	
	/**
	 * 登陆提交
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/loginSubmit")
	public String loginSubmit(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.LOGGER.info("----loginSubmit----");
		HttpSession session = request.getSession() ; 
		
		/* 接收参数 */
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String rand = request.getParameter("rand");
		
		/* 从Session取出验证码图片的验证 */
		String randSess = session.getAttribute("rand") + "";
		
		/* 对比验证码 
		 * 万能验证码
		 * */
		if((randSess!= null && randSess.equalsIgnoreCase(rand)) || "0715".equalsIgnoreCase(rand))
		{
			/* 根据邮箱查询管理员 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("email", email);
			AUsers users = this.usersService.findOneUsersService(condMap);
			/* 用户存在 */
			if(users != null)
			{
				/* 验证密码 */
				if(EncryptUtil.checkPass(password, users.getPassword()))
				{
					/* 密码正确 */
					if(users.getStatus() == AUsersEnum.STATUS_ENABLE.getStatus())
					{
						/* 启用 */
						/* 放入session */
						session.setAttribute("users", users);
						session.setAttribute("lastLoginTime", users.getLastLoginTime());
						
						/* 修改管理员信息 */
						users.setLastLoginTime(new Date());
						this.usersService.updateOneUsersService(users);
						
						/*admins.getCreateTime().toLocaleString():
						 * 2016-11-11 11:11:11
						 * */
						ConstatFinalUtil.LOGGER.info("登陆成功;id:{},邮箱:{},登陆时间:{}",users.getId(),users.getEmail(),
								users.getLastLoginTime().toLocaleString());
						
						if(this.returnUrl(request,response,users))
						{
							return null ; 
						}else
						{
							/* 登陆成功 */
							return "redirect:/head/users/main.htm";
						}
						
					}else
					{
						/* 禁用 
						 * 4:账户已禁用,请联系管理员
						 * */
						this.info = ConstatFinalUtil.INFO_JSON.getString("4") ; 
					}
				}else
				{
					/* 密码不正确 */
					this.info = ConstatFinalUtil.INFO_JSON.getString("5") ; 
				}
				
				/* 保留邮箱 */
				request.setAttribute("email", email);
			}else
			{
				/* 邮箱不存在,用户不存在 */
				this.info = ConstatFinalUtil.INFO_JSON.getString("6") ; 
			}
		}else
		{
			/* 验证码不正确 */
			this.info = ConstatFinalUtil.INFO_JSON.getString("7") ; 
		}
		
		request.setAttribute("info", info);
		
		/*String id = request.getParameter("id");
		if("1".equals(id))
		{
			 登陆成功 
			return "redirect:/back/admins/main.htm";
		}*/
		return this.login(request,response); 
	}
	
	/**
	 * -----------步骤2----------------
	 * 如果带上reurnUrl:跳转到returnUrl,并且加上token参数,页面跳转
	 * 如果木有带,跳转到用户中心自己登陆后的页面
	 * @param request
	 * @return 如果是true,表示有returnUrl,如果是false,表明木有returnUrl
	 * @throws IOException 
	 */
	private boolean returnUrl(HttpServletRequest request,HttpServletResponse response,AUsers users) throws IOException
	{
		String returnUrl = request.getParameter("returnUrl");
		ConstatFinalUtil.LOGGER.info("returnUrl===={}" , returnUrl);
		/* 不传为null,传了空字符串,两者合二为一 */
		if(returnUrl == null)
		{
			returnUrl = "" ; 
		}
		
		if(!"".equalsIgnoreCase(returnUrl))
		{
			/* 
			 * 生成uuid
			 * 加上token
			 * 	如果原来的url木有参数,加上?
			 * 	如果有参数,加上&
			 * 将returnUrl:加密
			 *  */
			/*生成uuid*/
			String token = UUID.randomUUID() + "" ; 
			
			/* 存储到Token的容器中,值为管理员对应的JSON信息 */
			/*JSONObject adminsJSON = new JSONObject();
			 存储管理员对象可开放的字段 
			adminsJSON.put("id", admins.getId());
			adminsJSON.put("email", admins.getEmail());
			adminsJSON.put("createTime", this.dateFormatUtil.format(admins.getCreateTime()));
			adminsJSON.put("updateTime", this.dateFormatUtil.format(admins.getUpdateTime()));
			adminsJSON.put("lastLoginTime", this.dateFormatUtil.format(admins.getLastLoginTime()));
			ConstatFinalUtil.TOKENS_MAP.put(token, adminsJSON);*/
			
			/* 调用POJO对应的json存储 */
			ConstatFinalUtil.TOKENS_MAP.put(token, users.toJSON());
			
			/*加上token*/
			String tokenIndex = "token=" ;
			if(returnUrl.indexOf("?") != -1 && returnUrl.indexOf(tokenIndex) != -1)
			{
				/* http://aaa.com?token=aaa
				 * http://aaa.com?id=1&a=2&token=2222
				 * http://aaa.com?id=1&a=2&abcdtoken=2222:自行解决
				 *  */
				returnUrl = returnUrl.substring(0, returnUrl.indexOf(tokenIndex));
				returnUrl = returnUrl + "token=" + token ; 
			}else if(returnUrl.indexOf("?") != -1)
			{
				/* http://aaa.com?id=10
				 * 木有token */
				/* 肯定有参数 */
				returnUrl = returnUrl + "&token=" + token ; 
			}else
			{
				/* 肯定木有参数 */
				returnUrl = returnUrl + "?token=" + token ; 
			}
			ConstatFinalUtil.LOGGER.info("returnUrl==加上token=={}",returnUrl);
			/* URL跳转 */
			response.sendRedirect(returnUrl);
			/* 将returnUrl:加密 */
			/*returnUrl = URLEncoder.encode(returnUrl, "UTF-8");*/
			return true ; 
		}
		return false ; 
	}
	
	/**
	 * 验证token是否有效
	 * 参数的名称为json,值为json字符串:
	 * {
			"version":"1",
			"data":{
				"token":""
			}
		}
	 * 
	 * @return	返回管理员对应的JSON
	 */
	@ResponseBody
	@RequestMapping(value="/validatorUsers",produces="text/html;charset=UTF-8")
	public String validatorUsers(HttpServletRequest request)
	{
		JSONObject resultJSON = new JSONObject() ; 
		String json = request.getParameter("json");
		if(json == null)
		{
			json = "" ; 
		}
		try
		{
			/* 将上行的json字符串,变成json */
			JSONObject reqJSON = (JSONObject) JSON.parse(json);
			
			/* 如果是第一个版本,调用第一个方法 */
			if("1".equalsIgnoreCase(reqJSON.getString("version")))
			{
				resultJSON = this.outerService.validatorUsers01Service(reqJSON);
			}/*else if("2".equalsIgnoreCase(reqJSON.getString("version")))
			{
				// 为客户端协议版本升级做准备
				this.outerService.validatorAdmins02Service(reqJSON);
			}*/
			else
			{
				resultJSON.put("version", reqJSON.getString("version"));
				resultJSON.put("code", "9");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("9"));
			}
		} catch (Exception e)
		{
			resultJSON.put("code", "11");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("11"));
		}
		return resultJSON + "" ; 
	}
	
	/**
	 * 注册
	 * @return
	 */
	@RequestMapping("/register")
	public String register()
	{
		ConstatFinalUtil.LOGGER.info("--- register ---");
		return "/head/register"; 
	}
	
	/**
	 * 注册提交
	 * @return
	 */
	@RequestMapping("/registerSubmit")
	public String registerSubmit(HttpServletRequest request,AUsers users)
	{
		ConstatFinalUtil.LOGGER.info("--- registerSubmit ---");
		
		HttpSession session = request.getSession() ; 
		String rand = request.getParameter("rand");
		/* 验证码操作 */
		/* 从Session取出验证码图片的验证 */
		String randSess = session.getAttribute("rand") + "";
		
		/* 对比验证码 
		 * 万能验证码
		 * */
		if((randSess!= null && randSess.equalsIgnoreCase(rand)) || "0715".equalsIgnoreCase(rand))
		{
			/* 
			 * 驱动已经成功赋值了邮箱,密码
			 *  */
			/* 密码加密 */
			users.setPassword(EncryptUtil.encodeStr(users.getPassword()));
			users.setStatus(AUsersEnum.STATUS_ENABLE.getStatus());
			users.setCreateTime(new Date());
			users.setUpdateTime(new Date());
			users.setLastLoginTime(new Date());
			
			/* 入库 */
			JSONObject resultJSON = this.usersService.saveOneUsersService(users);
			/* 提示用户 */
			this.info = resultJSON.getString("info");
			if("0".equalsIgnoreCase(resultJSON.get("code") + ""))
			{
				this.reSend(request,users.getEmail());
			}
		}else
		{
			this.info = ConstatFinalUtil.INFO_JSON.getString("7") ; 
		}
		request.setAttribute("info", info);
		return this.register(); 
	}

	/**
	 * 邮件重新发送
	 * @param users
	 */
	@RequestMapping("/reSend")
	public String reSend(HttpServletRequest request , String email)
	{
		/* 根据email,查询用户 */
		Map<String, Object> condMap = new HashMap<String,Object>();
		condMap.put("email", email);
		AUsers users = this.usersService.findOneUsersService(condMap);
		
		/* 生成链接
		 * http://127.0.0.1:10000/usersCenter_head/verifyEmail.htm?email=11@11.com&code=sha256(email+时间)
		 *  */
		Date sendEmailTime = new Date();
		/* sha256(11@11.com2017-02-09 11:11:11uuid) */
		String codeUid = UUID.randomUUID().toString() ; 
		String code = users.getEmail() + this.dateFormatUtil.format(sendEmailTime) + codeUid; 
		String verifyHref = ConstatFinalUtil.BUNDLE.getString("website.urlRootPath") + "/verifyEmail.htm?email=" + users.getEmail() + 
				"&code=" + DigestUtils.sha256Hex(code);
		/* 存储用户扩展表 */
		/*AUsersExtend usersExtend = new AUsersExtend();
		usersExtend.setUsersId(users.getId());*/
		AUsersExtend usersExtend = users.getUsersExtend() ;
		
		usersExtend.setEmailSendTime(sendEmailTime);
		usersExtend.setEmailSendCode(codeUid);
		
		usersExtend.setUpdateTime(new Date());
		/* 更新用户扩展表中的发送邮件相关的信息 */
		this.usersService.updateOneUsersService(users);
		
		/* 发邮件 */
		String fileName = "template/emailVerify.html" ;
		String subject = "欢迎使用用户中心(BJSXT)" ; 
		
		Map<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("subject", subject);
		paramsMap.put("email", users.getEmail());
		paramsMap.put("verifyHref", verifyHref);
		paramsMap.put("date", this.dateFormatUtil.formatDate(new Date()));
		String result = this.fileUtil.replaceFile(fileName, paramsMap);
		this.springEmailUtil.sendMailHtml(users.getEmail(),subject,result);
		this.info += ",发送邮件成功,请到邮箱中去验证;<a href='"+ request.getContextPath() +"/reSend.htm?email="+ users.getEmail() +"'>重新发送</a>";
		return this.register() ; 
	}
	
	/**
	 * 验证邮箱的链接
	 * @param request
	 * @param email
	 * @return
	 */
	@RequestMapping("/verifyEmail")
	public String verifyEmail(HttpServletRequest request,String email)
	{
		/* 根据email,查询用户 */
		Map<String, Object> condMap = new HashMap<String,Object>();
		condMap.put("email", email);
		AUsers users = this.usersService.findOneUsersService(condMap);
		if(users == null)
		{
			this.info = "邮箱不存在" ; 
		}else
		{
			AUsersExtend usersExtend = users.getUsersExtend() ; 
			
			/* --------检查过期时间------- */
			long exp = 1000 * 60 * 60 * 24 ; 
			if(new Date().getTime() - usersExtend.getEmailSendTime().getTime() > exp)
			{
				/* 链接超时 */
				this.info = "链接超时" ;
				request.setAttribute("info", info);
				return "/head/info" ; 
			}
			
			/* -------验证链接的合法性------ */
			/* sha256(11@11.com2017-02-09 11:11:11uuid) */
			String codeUid = usersExtend.getEmailSendCode() ; 
			String code = users.getEmail() + this.dateFormatUtil.format(usersExtend.getEmailSendTime()) + codeUid;
			code = DigestUtils.sha256Hex(code);
			
			String codeStr = request.getParameter("code");
			if(!code.equalsIgnoreCase(codeStr))
			{
				this.info = "链接非法" ;
				request.setAttribute("info", info);
				return "/head/info"; 
			}
			
			if(users.getEmailStatus() != AUsersEnum.EMAILSTATUS_VERIFYED.getStatus())
			{
				/* ------正常操作------- */
				users.setEmailStatus(AUsersEnum.EMAILSTATUS_VERIFYED.getStatus());
				JSONObject resDbJSON = this.usersService.updateOneUsersService(users);
				this.info = resDbJSON.getString("info");
			}else
			{
				this.info = "邮箱已经验证通过了,不需要验证" ; 
			}
		}
		request.setAttribute("info", info);
		return"/head/info" ; 
	}
}
